/*
 * Store DAO.java
 *
 * Created on February 13, 2007
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

/**
 *
 * @author craig marshall
 */
package finalintex2web;
import java.util.*;
import java.io.*;
import java.sql.*;
/**
 * Version 1.0
 *
 * The data base access object for stores
 */
public class StoreDAO {
    
    
    ///////////////////////////////////////
    ///   Singleton pattern
    
    private static StoreDAO instance = null;
    
    /** Creates a new instance of StoreDAO */
    private StoreDAO() {
    }
    
    /**
     * 
     * @return 
     */
    public static synchronized StoreDAO getInstance() {
        if (instance == null) {
            instance = new StoreDAO();
        }
        return instance;
    }
    
    
    /////////////////////////////////
    ///   CREATE
    
    /**
     * 
     * @return 
     */
    public StoreBO create() {
        String id = GUID.generate();
        StoreBO store = new StoreBO(id);
        Cache c = Cache.getInstance();
        c.put(store.getId(), store);
        return store;
    }
    
    
    /////////////////////////////////////
    ///   READ
    /** 
     * This is the public read statement.  It loads an existing record
     * from the database.
     */
    public synchronized StoreBO read(String id) throws DataException,ConnectionPoolException {
        if(Cache.getInstance().containsKey(id)){
            StoreBO store = (StoreBO)Cache.getInstance().get(id);
            return store;
        }
        
        try {
            Connection conn = ConnectionPool.getInstance().get();
            StoreBO store = (StoreBO)read(id,conn);
            ConnectionPool.getInstance().release(conn);
            return store;
        }catch (SQLException e) {
            // rollback
            throw new DataException("SQL error from read 1", e);
        }catch (ConnectionPoolException e){
            throw new ConnectionPoolException("Connection pool error in read 1", e);
        }
        
     
    }
    
    /** 
     *  This is a package method that is called by the public read (above) or
     *  by another DAO.  Either way we already have a connection to the database
     *  to use.  The user (controller) code never calls this one directly, since
     *  it can't know about Connection StoreDBOs or SQLExceptions.
     */
    public synchronized StoreBO read(String id, Connection conn) throws SQLException, DataException, ConnectionPoolException {
            if(Cache.getInstance().containsKey(id)){
            StoreBO store = (StoreBO)Cache.getInstance().get(id);
            return store;
            } 
                
           try{        
           PreparedStatement stmt = conn.prepareStatement("SELECT * FROM Store WHERE id=?");
           stmt.setString(1,id);
           ResultSet rs =  stmt.executeQuery();
           
           ConnectionPool.getInstance().release(conn);
            
            if (rs.next()) {
                StoreBO store = new StoreBO(id);
                store.setLocation(rs.getString("location"));
                store.setManager(rs.getString("manager"));
                store.setAddress(rs.getString("address"));
                store.setPhone(rs.getString("phone"));
                Cache.getInstance().put(id,store);      
                store.setIndb(true);
                stmt.close();
                return store;
               

            }else{
                throw new DataException("StoreBO was not found in the database.");
            }
           
            }catch (ConnectionPoolException e){
                throw new ConnectionPoolException("Could not retrieve a connection from the database", e);
            
            }catch (SQLException e){
                throw new DataException("SQL error", e);
            }
            
    }
        
    
    
    //////////////////////////////////
    ///   UPDATE
    
    /** 
     * This is the public save method.  It is what is called when
     * the user (controller) code wants to save or update an StoreDBO
     * into the database.
     */
    public synchronized void save(StoreBO store) throws DataException,ConnectionPoolException {
        
        
        try {
            Connection conn = ConnectionPool.getInstance().get();
            save(store,conn);
            ConnectionPool.getInstance().release(conn);
        }catch (SQLException e) {
            //rollback
            throw new DataException("Could not retrieve record for id=" + store.getId(), e);
            
            }catch (ConnectionPoolException e){
            throw new ConnectionPoolException("Could not retrieve record for id=" + e);
        }
        
        // release the connection back to the pool
        return;
    }
    
    /** 
     *  This is a package method that is called by the public save (above) or
     *  by another DAO.  Either way we already have a connection to the database
     *  to use.  The user (controller) code never calls this one directly, since
     *  it can't know about Connection StoreDBOs or SQLExceptions.
     *
     *  By having other DAOs call this save method (rather than update or
     *  insert below, each DAO in a chained save (like the StoreDAO calling
     *  MembershipDAO calling InterestDAO save chain) can independently decide
     *  whether to udpate or insert the BO it's saving.  That's why I made
     *  update and insert private rather than package level -- if you call
     *  them directly from another DAO, this DAO can't decide whether it's
     *  StoreDBO needs to be inserted or updated.
     */
     synchronized void save(StoreBO store, Connection conn) throws SQLException, DataException, ConnectionPoolException {
        // check the dirty flag in the StoreDBO.  if it is dirty, 
        // run update or insert
        if (store.isDirty()) {
            if (store.isIndb()) {
                update(store, conn);
            }else{
                insert(store, conn);
            }
            store.setDirty(false);
        
        
        Cache.getInstance().touch(store.getId());
     
        }
        
    }
    
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL udpate statement and make it more readable.  But
     * logically, it's really just a part of save.
     */
    private synchronized void update(StoreBO store, Connection conn) throws SQLException, DataException, ConnectionPoolException {
        PreparedStatement stmt = conn.prepareStatement("UPDATE Store SET location = ?, address = ?, phone = ?, manager = ? WHERE id=? ");
        stmt.setString(1,store.getLocation());
        stmt.setString(2,store.getAddress());
        stmt.setString(3,store.getPhone());
        stmt.setString(4,store.getManager());
        stmt.setString(5,store.getId());
        stmt.execute();
        stmt.close();
        ConnectionPool.getInstance().release(conn);
    }
     
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL insert statement and make it more readable.  But
     * logically, it's really just a part of save.
     */
    private synchronized void insert(StoreBO store, Connection conn) throws SQLException, DataException, ConnectionPoolException {
        // do the insert SQL statement
        PreparedStatement stmt = conn.prepareStatement("INSERT INTO Store (location,address,phone,manager,id) VALUES ( ?,?,?,?,?)");
        stmt.setString(1,store.getLocation());
        stmt.setString(2,store.getAddress());
        stmt.setString(3,store.getPhone());
        stmt.setString(4,store.getManager());
        stmt.setString(5,store.getId());
        stmt.execute();
        stmt.close();
        // tell the StoreDBO that it's now in the db (so we call update next time not insert)
        store.setIndb(true);
        ConnectionPool.getInstance().release(conn);
    }
    
    
    ////////////////////////////////////
    ///   DELETE
    // We are not implementing this feature in this class to help preserve data intergity.

}